import { ApiResponse, User, UserProfile } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import request from '@/utils/request'

export function getUser (): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<User>>('/user')
    console.log(res)
    const { data } = res.data
    dispatch({
      type: 'profile/getUser',
      payload: data
    })
  }
}

export const getUserProfile = (): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<UserProfile>>('/user/profile')
    res.data.data.intro = res.data.data.intro || ''
    dispatch({ type: 'profile/getUserProfile', payload: res.data.data })
  }
}

export function updateUserProfile (
  key: string,
  value: string
): RootThunkAction {
  return async (dispatch) => {
    await request.patch('/user/profile', {
      // [key]动态属性,可用于定义接收过来的参数key
      [key]: value
    })
    // 重新渲染
    dispatch(getUserProfile())
  }
}

export function updateUserPhoto (data: FormData): RootThunkAction {
  return async (dispatch) => {
    await request.patch('/user/photo', data)
    // 重新渲染
    dispatch(getUserProfile())
  }
}
